#!/bin/bash
VSA="10.0.100.102"

function wait_file(){
  wf_path="$1"
  wf_regex="$2"
  wfn=""
  while [ 1 ]
  do
    wfn=`find "$wf_path" | grep "$wf_regex" | head -n 1`
    if [ "$wfn" == "" ]
    then
      sleep 1
    else
      echo "$wfn"
      break
    fi
  done
  [ ! -h "$wfn" ] && exit -2
  return
}

[ "$1" == "" ] && echo "`basename $0`: Initiator_IQN" && exit -1
int_iqn="$1"

echo "InitiatorName=$int_iqn" > /etc/iscsi/initiatorname.iscsi
/etc/init.d/open-iscsi restart 1>/dev/null 2>&1
tgt_iqn=`iscsiadm -m discovery -t sendtargets -p $VSA|awk '{print $NF}'`

echo ISCSI_INITIATOR=$int_iqn
echo ISCSI_TARGET_NAME=$tgt_iqn
echo ISCSI_TARGET_IP=$VSA

iscsiadm -m node --login 1>/dev/null 2>&1
tgt_dev=`wait_file "/dev/disk/by-path/" "$tgt_iqn"`

echo "Target dev: $tgt_dev"
echo "n
p
1


w" | fdisk $tgt_dev

grub-install "$tgt_dev"

tgt_par=`wait_file "/dev/disk/by-path/" "$tgt_iqn.*part1"`
mkfs.ext4 "$tgt_par"

# Variables
src_dir="/iscsi/ubuntu12.ext4"
tgt_dir="/iscsi/temp"
boot_dir="/iscsi/boot"
isc_name=`echo "$tgt_iqn" | awk -F":" '{print $NF}'`

# copy os image
umount "$tgt_dir"
mount "$tgt_par" "$tgt_dir"
cp -a "$src_dir/*" "$tgt_dir"

# copy boot image
bin_linux=`find $tgt_dir/boot/ -name "vmlinuz*generic" | head -n 1`
bin_initrd=`find $tgt_dir/boot/ -name "initrd.img*generic" | head -n 1`
echo "Copying $bin_linux as kernel image......"
cp "$bin_linux" $boot_dir/linux
echo "Copying $bin_initrd as initrd image......"
cp "$bin_initrd" $boot_dir/initrd

# change host name
echo "Change host name to \"$isc_name\""
echo "$isc_name" > "$tgt_dir/etc/hostname"

# change disk id
par_uuid=`blkid "$tgt_par" | awk '{gsub("UUID=","",$2); gsub("\"","",$2); print $2}'`
echo "Change fstab to \"$par_uuid\""
cat "$tgt_dir/etc/fstab" | \
awk 'BEGIN{uuid="'"$par_uuid"'"}{\
  if (($2=="/")&&($1~/^UUID=.*/)){\
    gsub(/^UUID=[a-zA-Z0-9\-]+/,"UUID="uuid,$0);}\
  print $0}' > "$tgt_dir/etc/fstab"

# Log out
umount /iscsi/temp
iscsiadm -m node --logout

# really make iso
mv $boot_dir/isolinux.cfg $boot_dir/isolinux.bck
echo "PROMPT 0
DEFAULT linux
LABEL linux
  KERNEL linux
  APPEND root=UUID=$par_uuid rw ip=dhcp ISCSI_INITIATOR=$int_iqn ISCSI_TARGET_NAME=$tgt_iqn ISCSI_TARGET_IP=$VSA ISCSI_TARGET_PORT=3260 initrd=initrd
" > $boot_dir/isolinux.cfg

cd $boot_dir
mkisofs -o /pbfd/ISO/$isc_name.iso \
-b isolinux.bin \
-c boot.cat \
-no-emul-boot \
-boot-load-size 4 \
-boot-info-table \
./

mv ./isolinux.bck ./isolinux.cfg






